/*
 * 
 * 
 * 
 */
package com.hboxs.asl.controller.asl.member;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.Message;
import com.hboxs.asl.controller.asl.BaseController;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.Receiver;
import com.hboxs.asl.service.AreaService;
import com.hboxs.asl.service.MemberService;
import com.hboxs.asl.service.ReceiverService;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;

/**
 * Controller - 会员中心 - 收货地址
 */
@Controller("aslMemberReceiverController")
@RequestMapping("/weChat/receiver")
public class ReceiverController extends BaseController {

    protected Logger logger = Logger.getLogger(getClass().getName());

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "areaServiceImpl")
    private AreaService areaService;
    @Resource(name = "receiverServiceImpl")
    private ReceiverService receiverService;

    /**
     * 列表
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String list(ModelMap model) {
        try {
            Member member = memberService.getCurrent();
            model.addAttribute("receivers", member.getReceivers());
            model.addAttribute("member", member);
            return "/yijing/receivers";
        } catch (Exception e) {
            return "/yijing/404";
        }

    }

    /**
     * 找具体收货地址
     *
     * @param model
     * @param id
     * @return
     */
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public
    @ResponseBody
    Object findById(ModelMap model, Long id) {
        Member member = memberService.getCurrent();
        Receiver r = receiverService.find(id);
        if (member != r.getMember()) {
            return JsonMessage.error("无权访问");
        }
        return JsonMessage.success(r);
    }

    /**
     * 添加
     *
     * @param redirectAttributes
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.GET)
    public String add(RedirectAttributes redirectAttributes) {
        Member member = memberService.getCurrent();
        if (Receiver.MAX_RECEIVER_COUNT != null && member.getReceivers().size() >= Receiver.MAX_RECEIVER_COUNT) {
            addFlashMessage(redirectAttributes, Message.warn("shop.member.receiver.addCountNotAllowed", Receiver.MAX_RECEIVER_COUNT));
            return "redirect:list.htm";
        }
        return "yijing/html/receiver-add";
    }

    /**
     * 保存
     *
     * @param receiver
     * @param areaId
     * @return
     */
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public
    @ResponseBody
    Object save(Receiver receiver, Long areaId) {
        try {
            Member member = memberService.getCurrent();
            receiver.setMember(member);
            receiver.setIsDefault(false);
            receiver.setArea(areaService.find(areaId));
            String validateMsg = Receiver.validate(receiver);
            if (validateMsg != null) {
                return JsonMessage.error(validateMsg);
            }
            if (member.getReceivers().size() >= Receiver.MAX_RECEIVER_COUNT) {
                return JsonMessage.error("收货地址已经满了，请删除后再添加");
            }
            if (receiver.getZipCode() == null) {
                receiver.setZipCode("0");
            }
            receiverService.save(receiver);
            return JsonMessage.success(receiver);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 编辑
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/receivers", method = RequestMethod.GET)
    public
    @ResponseBody
    JsonMessage getReceivers(Long id) {
        try {
            Receiver receiver = receiverService.find(id);
            if (receiver == null) {
                return JsonMessage.error("地址信息不存在");
            }
            return JsonMessage.success(receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 设置默认收货地址
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/default", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage setDefault(Long id) {
        try {
            Receiver receiver = receiverService.find(id);
            if (receiver == null) {
                return JsonMessage.error("地址不存在");
            }
            if (!receiver.getIsDefault()) {
                Member member = memberService.getCurrent();
                for (Receiver receiver1 : member.getReceivers()) {
                    receiver1.setIsDefault(false);
                }
                receiver.setIsDefault(true);
                receiverService.update(receiver);
            }
            return JsonMessage.success("修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }


    /**
     * 更新收货地址信息
     *
     * @param receiver
     * @param id
     * @param areaId
     * @return
     */
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage update(Receiver receiver, Long id, Long areaId) {
        try {
            receiver.setZipCode("0");
            receiver.setArea(areaService.find(areaId));
            if (!isValid(receiver)) {
                return JsonMessage.error("地址信息错误");
            }
            Receiver pReceiver = receiverService.find(id);
            if (pReceiver == null) {
                return JsonMessage.error("地址信息不存在");
            }
            Member member = memberService.getCurrent();
            if (!member.equals(pReceiver.getMember())) {
                return JsonMessage.error("用户不存在");
            }
            receiverService.update(receiver, "member");
            return JsonMessage.success("地址信息修改成功！");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

    /**
     * 删除
     */
    @RequestMapping(value = "/delete", method = RequestMethod.POST)
    public
    @ResponseBody
    JsonMessage delete(Long id) {
        try {
            Member member = memberService.getCurrent();
            Receiver receiver = receiverService.find(id);
            if (!member.equals(receiver.getMember())) {
                return JsonMessage.error("地址信息不属于当前用户");
            }
            receiverService.delete(id);
            return JsonMessage.success("删除成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}